<!--  -->
<template>
  <div class="cart-container">
    <!-- 头部导航 -->
    <van-nav-bar
      :title="'购物车(' + cartList.length + ')'"
      fixed
      :z-index="999"
      @click-left="onClickLeft"
    >
      <template #left>
        <van-icon name="search" color="#ffffff" size="24" />
      </template>
      <template #right>
        <van-icon name="scan" color="#ffffff" size="24" />
      </template>
    </van-nav-bar>
    <!-- 商品列表 -->
    <div class="cart-list" v-if="cartList.length">
      <van-swipe-cell v-for="(item, index) in cartList" :key="item.id">
        <div class="good-item">
          <div class="choose">
            <van-checkbox
              v-model="item.isChecked"
              checked-color="#ee0a24"
              @click="chooseGood"
            ></van-checkbox>
          </div>
          <div class="avatar" @click="toGoodDetail(item.id)">
            <img
              :src="
                item.img ||
                'http://image5.suning.cn/uimg/b2c/newcatentries/0070061838-000000000104576473_2_400x400.jpg'
              "
              alt="商品封面图"
            />
          </div>
          <div class="info">
            <div class="name" @click="toGoodDetail(item.id)">
              {{ item.name }}
            </div>
            <div class="des">
              <div class="price">{{ item.price }}元</div>
              <div class="num-group">
                <van-button
                  :disabled="item.num <= 1"
                  @click="changeNum(item, 0, $event)"
                  >-</van-button
                >
                <van-button class="good-num nowrap">{{ item.num }}</van-button>
                <van-button
                  :disabled="item.num >= item.maxNum"
                  @click="changeNum(item, 1, $event)"
                  >+</van-button
                >
              </div>
            </div>
          </div>
        </div>
        <template #right>
          <van-button
            square
            text="删除"
            type="danger"
            class="delete-button"
            @click="deleteGood(index)"
          />
        </template>
      </van-swipe-cell>
    </div>
    <!-- 没有商品的提示文案 -->
    <div class="no-goods" v-else>
      <img src="../../assets/images/cart-empty.png" alt="购物车是空的" />
      <van-button class="shopping-at-once" @click="toShopping"
        >购物车是空的,马上去购物</van-button
      >
    </div>
    <!-- 结算栏 -->
    <div class="calc-bar">
      <van-submit-bar
        :price="totalPrice * 100"
        button-text="去结算"
        @submit="toCalc"
        label="合计:"
        :suffix-label="'共' + totalCount + '件'"
      >
        <van-checkbox
          v-model="isAllChecked"
          @click="chooseAll"
          checked-color="#ee0a24"
          >全选</van-checkbox
        >
      </van-submit-bar>
    </div>
    <!-- 底部导航 -->
    <!-- 底部tabbar -->
    <tabbar></tabbar>
    <!-- 对话框 -->
    <van-dialog
      v-model="showDialog"
      title="删除商品?"
      message="确定删除此件商品吗?删除后不可恢复"
      show-confirm-button
      show-cancel-button
      confirm-button-text="确认删除"
      @confirm="confirmDelete"
    >
    </van-dialog>
  </div>
</template>

<script>
import {
  NavBar,
  Icon,
  SwipeCell,
  Button,
  Checkbox,
  SubmitBar,
  Dialog,
  Toast,
} from "vant";
import tabbar from "@/components/tabbar/tabbar.vue";
export default {
  data() {
    return {
      cartList: [],
      userInfo: null,
      showDialog: false,
      isAllChecked: false,
    };
  },
  //生命周期 - 创建完成（访问当前this实例）
  created() {
    const cartList = JSON.parse(localStorage.getItem("cartList")) || [];
    const userInfo = JSON.parse(localStorage.getItem("userInfo"));
    this.cartList = cartList;
    this.userInfo = userInfo;
  },
  //生命周期 - 挂载完成（访问DOM元素）
  mounted() {
    //矫正全选按钮的状态
    this.isAllChecked = this.isAllCheckedFn();
  },
  methods: {
    onClickLeft() {
      this.$router.push("Search");
    },
    //选择商品
    chooseGood() {
      this.isAllChecked = this.isAllCheckedFn();
      // this.saveDataToCache();
    },
    //删除商品
    deleteGood(index) {
      this.showDialog = true;
    },
    //确定删除
    confirmDelete(index) {
      //执行真正的删除操作
      this.cartList.splice(index, 1);
      this.saveDataToCache();
      this.isAllChecked = this.isAllCheckedFn();
      Toast.success("删除商品成功");
    },
    //去购物
    toShopping() {
      this.$router.push("/");
    },
    //去商品详情页
    toGoodDetail(id) {
      this.$router.push({ name: "Detail", params: { id } });
    },
    //改变商品数量
    changeNum(item, num) {
      if (num) {
        //增加商品
        item.num++;
      } else {
        //减少商品
        item.num--;
      }
      this.saveDataToCache();
    },
    //全选/全不选
    chooseAll() {
      this.cartList.forEach((item) => {
        item.isChecked = this.isAllChecked;
      });
      // this.saveDataToCache();
    },
    //是否全选
    isAllCheckedFn() {
      return this.cartList.every((item) => item.isChecked);
    },
    //去结算
    toCalc() {
      let arr = [];
      if (this.totalCount) {
        this.cartList.forEach((item) => {
          if (item.isChecked) {
            arr.push(item);
          }
        });
        //更改vuex里面的值
        this.$store.commit("genGoodList", arr);
        this.$router.push({ name: "ConfirmOrder" });
      } else {
        Toast.fail("请选择商品");
      }
    },
    //保存数据到缓存
    saveDataToCache() {
      localStorage.setItem("cartList", JSON.stringify(this.cartList));
    },
  },
  components: {
    [NavBar.name]: NavBar,
    [Icon.name]: Icon,
    [SwipeCell.name]: SwipeCell,
    [Button.name]: Button,
    [Checkbox.name]: Checkbox,
    [SubmitBar.name]: SubmitBar,
    [Dialog.Component.name]: Dialog.Component,
    [Toast.name]: Toast,
    tabbar,
  },
  computed: {
    totalPrice() {
      let num = 0;
      this.cartList.forEach((item) => {
        if (item.isChecked) {
          num += item.price * item.num;
        }
      });
      return num;
    },
    totalCount() {
      let num = 0;
      this.cartList.forEach((item) => {
        if (item.isChecked) {
          num += item.num;
        }
      });
      return num;
    },
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      if (!vm.userInfo) {
        //去登录欢迎页
        vm.$router.push({ name: "Welcome" });
      }
    });
  },
};
</script>
<style scoped>
.cart-container {
  padding-top: 46px;
  padding-bottom: 100px;
}
.cart-container >>> .van-nav-bar {
  background-color: #ff6a00;
}
.cart-container >>> .van-nav-bar__title {
  color: #fff;
  font-size: 18px;
}
.van-nav-bar .icon {
  color: #fff;
  font-size: 18px;
  font-weight: bold;
}
/* 商品列表 */
.cart-list .van-card__title,
.van-card__num {
  font-size: 16px;
}
.goods-card {
  margin: 0;
  background-color: #fff;
}

.delete-button {
  height: 100%;
}
.no-goods {
  position: absolute;
  left: 0;
  right: 0;
  top: 46px;
  bottom: 56px;
  margin: 0 auto;
  overflow: hidden;
}
.no-goods img {
  width: 100vw;
  margin-top: 20px;
}
.shopping-at-once {
  width: 90%;
  height: 44px;
  margin: 60px 5%;
  color: #fff;
  text-align: center;
  line-height: 44px;
  border-radius: 20px;
  background-color: #ff6a00;
}
.good-item {
  display: flex;
  align-items: center;
  padding: 10px;
  font-size: 16px;
  border-bottom: 1px solid #ff6a00;
}
.good-item .avatar img {
  width: 100px;
  height: 100px;
  margin: 0 10px;
}
.good-item .info {
  display: flex;
  flex-direction: column;
  justify-content: center;
  width: 215px;
  height: 100px;
}
.good-item .info .name {
  font-weight: bold;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
}
.good-item .info .des {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10px;
}
.good-item .info .des .price {
  color: red;
  font-weight: bold;
}
.good-item .info .des .num-group .van-button {
  width: 30px;
  height: 30px;
  color: #fff;
  background-color: #ff6a00;
}
.good-item .info .des .num-group .good-num {
  margin: 0 4px;
}
/* 结算栏 */
.calc-bar .van-submit-bar {
  position: fixed;
  width: 100vw;
  height: 50px;
  bottom: 50px;
  background-color: #41b883;
  z-index: 999;
}
.van-submit-bar__button {
  width: 2.7rem;
  height: 0.9rem;
}
</style>